package cz.muni.fi.pa165.musiclibrary.musiclibraryweb.components;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;

/**
 * {@link AjaxSubmitLink} extension. Appends <code>error</code> to the form component
 * class attribute that has validation errors.
 * 
 * @author Maros Kucbel
 * @date 2012-11-26T18:49:13+0100
 */
public class AjaxSubmitLinkWithErrorClass extends AjaxSubmitLink {

    public AjaxSubmitLinkWithErrorClass(String id, Form<?> form) {
        super(id, form);
    }
    
    @Override
    protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
        form.visitChildren(new IVisitor<Component, Void>() {

            @Override
            public void component(Component object, IVisit<Void> visit) {
                object.add(new CssClassRemover("error"));
            }
        });
        target.add(form);
    }
    
    @Override
    protected void onError(final AjaxRequestTarget target, Form<?> form) {
        form.visitChildren(new IVisitor<Component, Void>() {

            @Override
            public void component(Component component, IVisit<Void> visit) {
                if (component instanceof FormComponent) {
                    FormComponent comp = (FormComponent) component;
                    if (comp.isValid()) {
                        comp.add(new CssClassRemover("error"));
                    } else {
                        comp.add(AttributeModifier.append("class", "error"));
                    }
                    target.add(comp);
                }
            }
        });
    }
    
}